<template>
  <div class="sku" style="margin-bottom: 20px;width: 130%">
    <div class="sku-container"
         style="overflow: hidden;padding: 20px;border: 1px solid #E4E7ED;box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1)">
      <div :key="index+'t'" class="theme" ref="theme" style="margin-top: 20px"
           v-for="(theme,index) in themeList">
        <el-form-item label="规格名称" label-width="80px" style="width: 220px">
          <el-input @blur="updateParent" @clear="removeTheme(index)" clearable
                    v-model="theme.name"></el-input>
        </el-form-item>
        <label style="margin-right: 20px">规格详情</label>
        <el-tag
            :disable-transitions="false"
            :key="ind"
            @close="handleClose(tag,index)"
            closable
            v-for="(tag,ind) in theme.items">
          {{tag.name}}
        </el-tag>
        <el-input
            :ref="'saveTagInput'+index"
            @keyup.enter.native="handleInputConfirm(index)"
            class="input-new-tag"
            size="small"
            v-if="theme.inputVisible"
            v-model="theme.inputValue"
        >
        </el-input>
        <el-button @click="showInput(index)" class="button-new-tag" size="small" v-else>+ 添加</el-button>
      </div>


      <el-button @click="addSkuTheme" round size="small" style="margin-top: 20px">添加规格</el-button>


      <div class="tag" v-if="themeList&&themeList.length>0">


        <el-divider></el-divider>

        <div :key="iddd" class="tag-group" style="margin-top: 20px" v-for="(theme,iddd) in themeList">
          <div v-if="theme.name&&theme.items.length>0">
            <span class="tag-group__title" style="margin-right: 20px;">{{theme.name}}</span>
            <el-tag
                :key="idx"
                :type="types[idx]"
                effect="dark"
                v-for="(item,idx) in theme.items">
              {{ item.name }}
            </el-tag>
          </div>
        </div>
      </div>


      <div class="sku-list" v-if="themeList&&themeList.length>0">


        <el-divider v-if="themeList"></el-divider>

        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="价格">
            <el-input :min="0" @keyup.native="bathSet('price')" placeholder=""
                      style="width: 80px" v-model="bathForm.price"></el-input>
          </el-form-item>
          <el-form-item label="积分">
            <el-input @keyup.native="bathSet('point')" placeholder="" style="width: 80px"
                      v-model="bathForm.point"></el-input>
          </el-form-item>
          <!--                    <el-form-item label="利润">-->
          <!--                        <el-input @keyup.native="bathSet('profit')" v-model="bathForm.profit" style="width: 80px" placeholder=""></el-input>-->
          <!--                    </el-form-item>-->
          <el-form-item label="库存">
            <el-input @keyup.native="bathSet('stock')" placeholder="" style="width: 80px"
                      v-model="bathForm.stock"></el-input>
          </el-form-item>
          <!--                    <el-form-item label="重量">-->
          <!--                        <el-input @keyup.native="bathSet('weight')"  v-model="bathForm.weight" style="width: 80px" placeholder=""></el-input>-->
          <!--                    </el-form-item>-->
        </el-form>

        <el-table :data="tempSkuList"
                  border
                  style="width: 100%; margin-top: 20px"
                  v-if="themeList">
          <el-table-column
              :label="labelName"
              :width="labelName.length*20+10+'px'"
              align="center"
              v-if="labelName">
            <template slot-scope="scope">
              <span>{{scope.row.name}}</span>
            </template>
          </el-table-column>

          <el-table-column
              align="center"
              label="价格"
              width="90px">
            <template slot-scope="scope">
              <el-input :disabled="tempSkuList[scope.$index].disable"
                        @blur="updateParent" @keyup.native="numberSet('price',scope.$index)"
                        v-model="tempSkuList[scope.$index].price"></el-input>
            </template>
          </el-table-column>

          <el-table-column
              align="center"
              label="积分"
              width="90px">
            <template slot-scope="scope">
              <el-input :disabled="tempSkuList[scope.$index].disable" @blur="updateParent"
                        @keyup.native="numberSet('point',scope.$index)"
                        v-model="tempSkuList[scope.$index].point"></el-input>
            </template>
          </el-table-column>

          <!--                    <el-table-column-->
          <!--                            align="center"-->
          <!--                            label="重量"-->
          <!--                            width="90px">-->
          <!--                        <template slot-scope="scope">-->
          <!--                            <el-input :disabled="tempSkuList[scope.$index].disable" @blur="updateParent"-->
          <!--                                      @keyup.native="numberSet('point',scope.$index)"-->
          <!--                                      v-model="tempSkuList[scope.$index].weight"></el-input>-->
          <!--                        </template>-->
          <!--                    </el-table-column>-->

          <!--                    <el-table-column-->
          <!--                            width="90px"-->
          <!--                            align="center"-->
          <!--                            label="利润">-->
          <!--                        <template slot-scope="scope">-->
          <!--                            <el-input :disabled="tempSkuList[scope.$index].disable" @blur="updateParent"-->
          <!--                                      v-model="tempSkuList[scope.$index].profit"></el-input>-->
          <!--                        </template>-->
          <!--                    </el-table-column>-->

          <el-table-column
              align="center"
              label="库存"
              width="90px">
            <template slot-scope="scope">
              <el-input :disabled="tempSkuList[scope.$index].disable"
                        @blur="updateParent" @keyup.native="numberSet('stock',scope.$index)"
                        v-model="tempSkuList[scope.$index].stock"></el-input>
            </template>
          </el-table-column>

          <!--                    <el-table-column-->
          <!--                            width="90px"-->
          <!--                            align="center"-->
          <!--                            label="重量">-->
          <!--                        <template slot-scope="scope">-->
          <!--                            <el-input :disabled="tempSkuList[scope.$index].disable" @blur="updateParent"-->
          <!--                                      v-model="tempSkuList[scope.$index].weight"></el-input>-->
          <!--                        </template>-->
          <!--                    </el-table-column>-->

          <el-table-column
              align="center"
              label="图片"
              width="90px">
            <template slot-scope="scope">
              <!--                                            <el-form-item label="产品主图" prop="img">-->
              <el-upload
                  :auto-upload="true"
                  :before-upload="handleUpload"
                  :class="{hide:tempSkuList[scope.$index].img}"
                  :data="qiData"
                  :disabled="tempSkuList[scope.$index].disable"
                  :file-list="tempSkuList[scope.$index].img?[{url:domain+tempSkuList[scope.$index].img}]:[]"
                  :limit="1"
                  :on-preview="(file, fileList)=>handlePictureCardPreview(file, fileList,scope.$index)"
                  :on-remove="(file, fileList)=>handleimgRemove(file, fileList,scope.$index)"
                  :on-success="(response, file, fileList)=>{return handleimgUploadSuccess(response, file, fileList,scope.$index)}"
                  @click="selectImg(scope.$index)"
                  action="http://upload.qiniup.com"
                  list-type="picture-card"
                  ref="imgUpload">
                <i class="el-icon-plus"></i>
              </el-upload>
              <!--                                            </el-form-item>-->
            </template>
          </el-table-column>


          <el-table-column
              align="center"
              label="禁用">
            <template slot-scope="scope">
              <el-switch
                  v-model="tempSkuList[scope.$index].disable"
              >
              </el-switch>

            </template>
          </el-table-column>

        </el-table>
      </div>


    </div>

    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img :src="dialogImageUrl" alt="" width="100%">
    </el-dialog>
  </div>
</template>

<style lang="stylus">
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.sku .el-upload--picture-card {
  width 60px;
  height 60px;
  line-height 60px;
}

.sku .el-upload-list__item {
  width 60px;
  height 60px;
  line-height 60px;
}

.hide .el-upload--picture-card {
  display: none;
}

</style>

<script>
import sku from "../../utils/sku";
import {domain} from "../../api/qiniu";
import {clearNoNum} from '../../utils/number'

export default {
  props: {

    qData: {
      type: Object
    },
    skuList: Array,
    itemList: {
      type: Array
    }
  },
  created() {
    //item => theme 按主题分组
    this.itemToTheme()
    //初始化skuList
    if (this.skuList) {
      this.tempSkuList = this.skuList.slice()
    }
  },
  data() {

    return {
      tempSkuList: [],
      themeList: [],
      bathForm: {
        stock: 0,
        price: 0.0,
        point: 0.0,
        weight: 0.0,
        profit: 0.0
      },
      dialogVisible: false,
      dialogImageUrl: '',
      qiData: this.qData,
      types: ['', 'success', 'info', 'danger', 'warning']
    }
  },
  computed: {
    domain() {
      return domain
    },
    labelName() {
      let str = '';
      this.themeList.forEach(theme => {
        if (!theme.name || !theme.items.length > 0) {
          return
        }
        str = str + theme.name + '-';
      })
      return str.substr(0, str.length - 1)
    }

  },
  methods: {
    themeToItem() {
      let items = []
      this.themeList.forEach(theme => {
        items = items.concat(theme.items)
      })
      return items;
    },
    itemToTheme() {
      let map = {}
      if (this.itemList) {
        //用map去重合并
        this.itemList.forEach(item => {
          let list = []
          if (map[item.theme]) { //存在
            list = map[item.theme]
          }
          list.push(item)
          map[item.theme] = list
        })
        //转换成theme对象
        for (let key in map) {
          let ob = {name: key, items: map[key]}
          this.themeList.push(ob)
        }
      }
    },
    bathSet(key) {
      this.bathForm[key] = clearNoNum(this.bathForm[key])
      for (let i = 0; i < this.tempSkuList.length; i++) {
        if (this.tempSkuList[i].disable) {
          continue
        }
        this.tempSkuList[i][key] = this.bathForm[key]
      }
    },
    numberSet(key, index) {

      // this.tempSkuList[index][key] = clearNoNum(this.tempSkuList[index][key])
      this.$set(this.tempSkuList[index], key, clearNoNum(this.tempSkuList[index][key]))
      // console.log(index+'??'+this.tempSkuList[index][key])
    },
    //重组Sku
    updateSku() {
      //刷新内部组件
      this.tempSkuList = this.initSku()
      this.updateParent()
    },
    //重组或者值改变的时候通知上级数据更新
    updateParent() {
      //更新父组件
      this.$emit('updateSku', this.themeToItem(), this.tempSkuList)
    },
    initSku() {
      //取出主题的规格名
      let ski = []
      this.themeList.forEach(theme => {
        if (!theme.items) {
          return
        }
        ski.push(theme.items.map(item => item.name))
      })
      //重组规格组合名
      let skuNames = sku(ski)
      //转成对象
      let res = skuNames.map(name => {
        let item = {
          name: name,
          stock: 0,
          price: 0.0,
          point: 0.0,
          profit: 0.0,
          weight: 0.0,
          img: '',
          disable: false
        }
        //如果名称没有改变 依旧保留
        for (let i in this.tempSkuList) {
          let mallSku = this.tempSkuList[i]
          if (mallSku.name == item.name) {
            Object.assign(item, mallSku)
          }
        }
        return item
      })

      return res;
    },
    addSkuTheme() {
      let skuTheme = {
        inputVisible: false,
        inputValue: '',
        name: '',
        items: []
      }
      this.themeList.push(skuTheme)
      // this.updateSku()
    },
    removeTheme(index) {
      this.themeList.splice(index, 1)
      //重组Skus
      this.updateSku()
    },
    handleClose(tag, index) {
      let tags = this.themeList[index].items
      tags.splice(tags.indexOf(tag), 1);
      //重组Skus
      this.updateSku()
    },

    showInput(index) {
      // this.themeList[index].inputVisible = true;
      this.$set(this.themeList[index], 'inputVisible', true)
      this.$nextTick(_ => {
        this.$refs['saveTagInput' + index][0].$refs.input.focus();
      });
    },

    handleInputConfirm(index) {
      let tags = this.themeList[index].items
      let inputValue = this.themeList[index].inputValue;
      if (inputValue) {
        tags.push({theme: this.themeList[index].name, name: inputValue});
      }
      this.themeList[index].inputVisible = false;
      this.themeList[index].inputValue = '';
      //重组Skus
      this.updateSku()
    },
    handleimgUploadSuccess(response, file, fileList, index) {
      this.tempSkuList[index].img = file.response.key
    },
    handleimgRemove(file, fileList, index) {
      this.tempSkuList[index].img = ''
    },
    handleUpload(file) {
      this.qData.key = new Date().valueOf() + file.name
    },
    handlePictureCardPreview(file, fileList, index) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}

</script>
